package test.socket;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketAddress;

public class TCPEchoServer {
	private static final int BUFSIZE=32;
	private static ServerSocket serverSocket;
	
	public static void main(String [] args) throws IOException, InterruptedException{
		int servPort=8337;
		
		//1.创建一个ServerSocket实例并制定本地端口。此套接字的功能是侦听该制定端口收到的连接。
		int recvMsgSize;
		
		byte [] receiveBuf=new byte[BUFSIZE];
		
		//2.重复执行
		while(true){
			serverSocket = new ServerSocket(servPort);
			Socket clntSock=serverSocket.accept();
			SocketAddress clientAddress=clntSock.getRemoteSocketAddress();
			System.out.println("Handling client at "+clientAddress);
			
			//b,使用所返回的Socket实例的InputStream和OutputStream与客户端进行通信
			InputStream in=clntSock.getInputStream();
			OutputStream out=clntSock.getOutputStream();

			while((recvMsgSize=in.read(receiveBuf))!=-1){
				out.write(receiveBuf, 0, recvMsgSize);
			}
		
			//c，通信完成后，使用Socket的close()方法关闭该客户端套接字链接
			clntSock.close();
		}
	}
}